﻿using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using FNN.Networks;
using FNN.NetworkMasters;
using System.Threading.Tasks;
using System;
using FNN.Factories.Helpers;
using FNN.Helpers.IO;

namespace GraphicFNN.Pages
{
    /// <summary>
    /// Логика взаимодействия для TrainingPage.xaml
    /// </summary>
    public partial class TrainingPage : Page
    {
        public SerializationHelper serializationHelper = new SerializationHelper();

        public TrainingPage()
        {
            InitializeComponent();
        }

        private void BtnStartTraining_OnClick(object sender, RoutedEventArgs e)
        {
            Network targetNetwork = serializationHelper.LoadBinary(TxtNetworkPath.Text); ;
            NetworkMaster netMaster = null;
            ChartWindow chartWindow = new ChartWindow();

            var helper = DataSourceHelperFactory.CreateHelper(
                (NetworkTypes)CmbType.SelectedIndex,
                TxtSourcePath.Text
                );
            var currentDataSource = helper.GetDataSource();

            switch ((NetworkTypes)CmbType.SelectedIndex)
            {
                case NetworkTypes.Financial:
                    netMaster = new FinancialNetworkMaster { PopulationCount = 3 };
                    ((FinancialNetworkMaster)netMaster).IterationResultsImproved += chartWindow.CatchResultsImproved;
                    ((FinancialNetworkMaster)netMaster).IterationChanged += chartWindow.CatchIterationChanged;
                    ((FinancialNetworkMaster)netMaster).DataSource = currentDataSource;
                    ((FinancialNetworkMaster)netMaster).TargetResult = Convert.ToInt32(TxtResultPercent.Text);
                    break;
                case NetworkTypes.Regular:
                    netMaster = new RegularNetworkMaster { PopulationCount = 3 };
                    ((RegularNetworkMaster)netMaster).IterationResultsImproved += chartWindow.CatchResultsImproved;
                    ((RegularNetworkMaster)netMaster).IterationChanged += chartWindow.CatchIterationChanged;
                    ((RegularNetworkMaster)netMaster).DataSource = currentDataSource;
                    ((RegularNetworkMaster)netMaster).TargetResult = Convert.ToDouble(TxtResultPercent.Text.Replace(",", "."));
                    break;
            }

            if ((netMaster == null) || (targetNetwork == null))
            {
                MessageBox.Show("Ошибка! Файл поврежден или имел неверный формат!");
                return;
            }

            netMaster.TargetResult = Convert.ToDouble(TxtResultPercent.Text);
            netMaster.IterationsLimit = Convert.ToInt32(TxtIterations.Text);
            netMaster.TimeLimit = Convert.ToInt32(TxtTime.Text);
            chartWindow.Show();

            var backgroundTask = Task.Factory.StartNew(() =>
            {
                var targetName = String.Empty;
                var targetPath = String.Empty;
                var serializationHelper = new SerializationHelper();

                var resultNetwork = netMaster.TrainMultiNetwork(targetNetwork);

                Dispatcher.Invoke(() =>
                {
                    targetName = targetNetwork.NetworkName;
                    targetPath = TxtNetworkPath.Text;
                    serializationHelper.WriteBinary(resultNetwork, targetPath);
                    chartWindow.Close();
                });
            });
        }

        private void BtnBrowseFile_OnClick(object sender, RoutedEventArgs e)
        {
            var fileBrowser = new OpenFileDialog()
            {
                CheckFileExists = true,
                Multiselect = false,
                Filter = "FNN|*.fnn|XML|*.xml|SOAP|*.soap"
            };
            fileBrowser.ShowDialog();
            TxtNetworkPath.Text = fileBrowser.FileName;
        }

        private void BtnBrowseSource_OnClick(object sender, RoutedEventArgs e)
        {
            var fileBrowser = new OpenFileDialog()
            {
                CheckFileExists = true,
                Multiselect = false,
                Filter = "CSV|*.csv"
            };
            fileBrowser.ShowDialog();
            TxtSourcePath.Text = fileBrowser.FileName;
        }
    }
}
